/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package unipiloto.edu.co.auth.service.admin;

import org.osgi.framework.BundleContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import unipiloto.edu.co.auth.service.tracker.ServiceLocator;

/**
 *
 * @author David
 */
@WebServlet(name = "RegistrationServlet", urlPatterns = "/registration")
public class RegistrationServlet extends HttpServlet {

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, java.io.IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Registro de usuarios</title>");
        out.println("</head>");
        out.println("<body bgcolor=white>");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        try {
            ServiceLocator locator = new ServiceLocator(getBundleContext());
            try {
                if (locator.getUserAuthenticacionService(-1).register(username, password)) {
                    out.println("Nuevo usuario registrado: " + username);
                } else {
                    out.println("No se pudo registrar el usuario: " + username);
                }
            } catch (ServiceLocator.ServiceUnavailableException e) {
                out.println("El servicio no se encuentra disponible...");
            }

        } catch (Exception e) {
            e.printStackTrace(out);
        }
        out.println("</body>");
        out.println("</html>");
    }

    private BundleContext getBundleContext() {
        return BundleContext.class.cast(getServletConfig().getServletContext().getAttribute("osgi-bundlecontext"));
    }
}
